package pipeline

import (
	"context"
	"sync"
	"time"

	"mcp-server/internal/metadata"
)

// ProcessingStage 处理阶段枚举
type ProcessingStage string

const (
	StageQueued      ProcessingStage = "queued"      // 排队中
	StageReading     ProcessingStage = "reading"     // 读取文件
	StageParsing     ProcessingStage = "parsing"     // 解析文档
	StageMetadata    ProcessingStage = "metadata"    // 提取元数据
	StageSplitting   ProcessingStage = "splitting"   // 文本分片
	StageVectorizing ProcessingStage = "vectorizing" // 向量化
	StageStoring     ProcessingStage = "storing"     // 存储
	StageCompleted   ProcessingStage = "completed"   // 完成
	StageFailed      ProcessingStage = "failed"      // 失败
)

// ProcessingStatus 处理状态
type ProcessingStatus string

const (
	StatusPending    ProcessingStatus = "pending"    // 等待中
	StatusProcessing ProcessingStatus = "processing" // 处理中
	StatusCompleted  ProcessingStatus = "completed"  // 已完成
	StatusFailed     ProcessingStatus = "failed"     // 失败
	StatusCancelled  ProcessingStatus = "cancelled"  // 已取消
)

// TaskProgress 任务进度信息
type TaskProgress struct {
	TaskID          string                     `json:"task_id"`
	FileName        string                     `json:"file_name"`
	Stage           ProcessingStage            `json:"stage"`
	Status          ProcessingStatus           `json:"status"`
	Progress        float64                    `json:"progress"` // 0-100
	ProcessedChunks int                        `json:"processed_chunks"`
	TotalChunks     int                        `json:"total_chunks"`
	StartTime       time.Time                  `json:"start_time"`
	UpdateTime      time.Time                  `json:"update_time"`
	EndTime         *time.Time                 `json:"end_time,omitempty"`
	ErrorMessage    string                     `json:"error_message,omitempty"`
	Metadata        *metadata.DocumentMetadata `json:"metadata,omitempty"`
}

// PipelineTask 流水线任务
type PipelineTask struct {
	ID         string             `json:"id"`
	FilePath   string             `json:"file_path"`
	FileName   string             `json:"file_name"`
	Content    string             `json:"content,omitempty"`
	Config     *TaskConfig        `json:"config"`
	Progress   *TaskProgress      `json:"progress"`
	Result     *TaskResult        `json:"result,omitempty"`
	Context    context.Context    `json:"-"`
	CancelFunc context.CancelFunc `json:"-"`
	CreatedAt  time.Time          `json:"created_at"`
	UpdatedAt  time.Time          `json:"updated_at"`
	mutex      sync.RWMutex       `json:"-"`
}

// TaskConfig 任务配置
type TaskConfig struct {
	// 文档处理配置
	MaxChunkSize int    `json:"max_chunk_size"` // 最大分片大小
	ChunkOverlap int    `json:"chunk_overlap"`  // 分片重叠
	Language     string `json:"language"`       // 语言设置

	// 元数据提取配置
	ExtractMetadata bool                      `json:"extract_metadata"`
	MetadataConfig  *metadata.ExtractorConfig `json:"metadata_config,omitempty"`

	// 向量化配置
	VectorDimension int    `json:"vector_dimension"` // 向量维度
	EmbeddingModel  string `json:"embedding_model"`  // 嵌入模型

	// 存储配置
	CollectionName string `json:"collection_name"` // 集合名称
	BatchSize      int    `json:"batch_size"`      // 批处理大小

	// 重试配置
	MaxRetries int           `json:"max_retries"` // 最大重试次数
	RetryDelay time.Duration `json:"retry_delay"` // 重试延迟

	// 并发配置
	MaxConcurrency int `json:"max_concurrency"` // 最大并发数
}

// TaskResult 任务结果
type TaskResult struct {
	TaskID           string                     `json:"task_id"`
	Success          bool                       `json:"success"`
	ProcessedChunks  int                        `json:"processed_chunks"`
	GeneratedVectors int                        `json:"generated_vectors"`
	ProcessingTime   time.Duration              `json:"processing_time"`
	Metadata         *metadata.DocumentMetadata `json:"metadata,omitempty"`
	ErrorDetails     []string                   `json:"error_details,omitempty"`
	Statistics       *ProcessingStatistics      `json:"statistics,omitempty"`
}

// ProcessingStatistics 处理统计信息
type ProcessingStatistics struct {
	ReadTime        time.Duration `json:"read_time"`
	ParseTime       time.Duration `json:"parse_time"`
	MetadataTime    time.Duration `json:"metadata_time"`
	SplitTime       time.Duration `json:"split_time"`
	VectorizeTime   time.Duration `json:"vectorize_time"`
	StoreTime       time.Duration `json:"store_time"`
	TotalTime       time.Duration `json:"total_time"`
	ChunkCount      int           `json:"chunk_count"`
	VectorCount     int           `json:"vector_count"`
	FileSize        int64         `json:"file_size"`
	ProcessingSpeed float64       `json:"processing_speed"` // MB/s
}

// PipelineConfig 流水线配置
type PipelineConfig struct {
	// 并发控制
	MaxConcurrentTasks int `json:"max_concurrent_tasks"`
	WorkerPoolSize     int `json:"worker_pool_size"`
	QueueSize          int `json:"queue_size"`

	// 超时设置
	TaskTimeout  time.Duration `json:"task_timeout"`
	StageTimeout time.Duration `json:"stage_timeout"`

	// 重试设置
	DefaultMaxRetries int           `json:"default_max_retries"`
	DefaultRetryDelay time.Duration `json:"default_retry_delay"`

	// 监控设置
	ProgressUpdateInterval time.Duration `json:"progress_update_interval"`
	MetricsEnabled         bool          `json:"metrics_enabled"`

	// 存储设置
	CheckpointEnabled  bool          `json:"checkpoint_enabled"`
	CheckpointInterval time.Duration `json:"checkpoint_interval"`
	CheckpointPath     string        `json:"checkpoint_path"`

	// 默认任务配置
	DefaultTaskConfig *TaskConfig `json:"default_task_config"`
}

// PipelineMetrics 流水线指标
type PipelineMetrics struct {
	TotalTasks       int64         `json:"total_tasks"`
	CompletedTasks   int64         `json:"completed_tasks"`
	FailedTasks      int64         `json:"failed_tasks"`
	ActiveTasks      int64         `json:"active_tasks"`
	QueuedTasks      int64         `json:"queued_tasks"`
	AverageTime      time.Duration `json:"average_time"`
	ThroughputPerMin float64       `json:"throughput_per_min"`
	ErrorRate        float64       `json:"error_rate"`
	LastUpdateTime   time.Time     `json:"last_update_time"`
}

// ProcessorInterface 处理器接口
type ProcessorInterface interface {
	Process(ctx context.Context, task *PipelineTask) error
	GetName() string
	GetStage() ProcessingStage
}

// ProgressMonitor 进度监控器接口
type ProgressMonitor interface {
	UpdateProgress(taskID string, progress *TaskProgress)
	GetProgress(taskID string) (*TaskProgress, error)
	GetAllProgress() map[string]*TaskProgress
	Subscribe(taskID string) <-chan *TaskProgress
	Unsubscribe(taskID string)
}

// CheckpointManager 检查点管理器接口
type CheckpointManager interface {
	SaveCheckpoint(task *PipelineTask) error
	LoadCheckpoint(taskID string) (*PipelineTask, error)
	DeleteCheckpoint(taskID string) error
	ListCheckpoints() ([]string, error)
}

// Pipeline 流水线接口
type Pipeline interface {
	// 任务管理
	SubmitTask(filePath string, config *TaskConfig) (string, error)
	CancelTask(taskID string) error
	GetTask(taskID string) (*PipelineTask, error)
	ListTasks() ([]*PipelineTask, error)

	// 批量处理
	SubmitBatch(filePaths []string, config *TaskConfig) ([]string, error)

	// 进度监控
	GetProgress(taskID string) (*TaskProgress, error)
	GetMetrics() *PipelineMetrics

	// 生命周期管理
	Start() error
	Stop() error
	IsRunning() bool

	// 配置管理
	UpdateConfig(config *PipelineConfig) error
	GetConfig() *PipelineConfig
}

// 辅助方法
func (t *PipelineTask) UpdateProgress(stage ProcessingStage, progress float64) {
	t.mutex.Lock()
	defer t.mutex.Unlock()

	t.Progress.Stage = stage
	t.Progress.Progress = progress
	t.Progress.UpdateTime = time.Now()
	t.UpdatedAt = time.Now()
}

func (t *PipelineTask) SetStatus(status ProcessingStatus) {
	t.mutex.Lock()
	defer t.mutex.Unlock()

	t.Progress.Status = status
	t.Progress.UpdateTime = time.Now()
	t.UpdatedAt = time.Now()

	if status == StatusCompleted || status == StatusFailed || status == StatusCancelled {
		now := time.Now()
		t.Progress.EndTime = &now
	}
}

func (t *PipelineTask) SetError(err error) {
	t.mutex.Lock()
	defer t.mutex.Unlock()

	t.Progress.Status = StatusFailed
	t.Progress.ErrorMessage = err.Error()
	t.Progress.UpdateTime = time.Now()
	t.UpdatedAt = time.Now()

	now := time.Now()
	t.Progress.EndTime = &now
}

func (t *PipelineTask) GetProgress() *TaskProgress {
	t.mutex.RLock()
	defer t.mutex.RUnlock()

	// 返回进度的副本
	progress := *t.Progress
	return &progress
}

// DefaultTaskConfig 返回默认任务配置
func DefaultTaskConfig() *TaskConfig {
	return &TaskConfig{
		MaxChunkSize:    1000,
		ChunkOverlap:    100,
		Language:        "zh",
		ExtractMetadata: true,
		MetadataConfig:  metadata.DefaultExtractorConfig(),
		VectorDimension: 1536,
		EmbeddingModel:  "text-embedding-ada-002",
		CollectionName:  "documents",
		BatchSize:       10,
		MaxRetries:      3,
		RetryDelay:      time.Second * 2,
		MaxConcurrency:  4,
	}
}

// DefaultPipelineConfig 返回默认流水线配置
func DefaultPipelineConfig() *PipelineConfig {
	return &PipelineConfig{
		MaxConcurrentTasks:     10,
		WorkerPoolSize:         5,
		QueueSize:              100,
		TaskTimeout:            time.Minute * 30,
		StageTimeout:           time.Minute * 5,
		DefaultMaxRetries:      3,
		DefaultRetryDelay:      time.Second * 2,
		ProgressUpdateInterval: time.Second * 1,
		MetricsEnabled:         true,
		CheckpointEnabled:      true,
		CheckpointInterval:     time.Minute * 5,
		CheckpointPath:         "./checkpoints",
		DefaultTaskConfig:      DefaultTaskConfig(),
	}
}
